import React, { useCallback, useEffect, useState } from 'react';
import { Button, Card, Form, Grid, Input, message, Modal, Space, Table, Tag, Typography } from 'antd';
import { DeleteOutlined, EditOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { addUser, deleteUser, getCurrentUser, getUserList, updateUser } from '../../api/user';
import { UserListInfo } from "../../types";
import { useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '../../store';
import EditUserForm from './EditUserForm';
import AddUserForm from './AddUserForm';

const { useBreakpoint } = Grid;
const { Title } = Typography;

const UserList: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const token = useSelector((state: RootState) => state.auth.token);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const screens = useBreakpoint();
  // 确保screens对象可用，提供默认值
  const isMobile = screens.xs === true;

  const [modalForm] = Form.useForm();

  const [users, setUsers] = useState<UserListInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [filteredUsers, setFilteredUsers] = useState<UserListInfo[]>([]);
  

  // 检查权限并获取用户列表
  useEffect(() => {
    const localToken = localStorage.getItem('token');
    if (!localToken && !token) {
      message.error('无权限访问，请先登录');
      navigate('/login');
      return;
    }

    const fetchUsers = async () => {
      setLoading(true);
      try {
        const data = await getUserList();
        console.log('获取用户列表成功:', data.data);
        setUsers(data.data);
        setFilteredUsers(data.data);
      } catch (error) {
        console.error('Failed to fetch users:', error);
        message.error('获取用户列表失败');
      } finally {
        setLoading(false);
      }
    };

    const fetchCurrentUser = async () => {
      try {
        const currentUser = await getCurrentUser();
        dispatch({ type: 'auth/updateUser', payload: currentUser });
      } catch (error) {
        console.error('Failed to fetch current user:', error);
        message.error('获取当前用户信息失败');
      }
    };

    // 合并两个请求到一个 useEffect 中
    const fetchData = async () => {
      await Promise.all([fetchUsers(), fetchCurrentUser()]);
    };

    fetchData();
  }, [token, navigate, dispatch]);

  // 处理搜索过滤
  useEffect(() => {
    const filtered = users.filter(user =>
      (user.nickName?.toLowerCase() || '').includes(searchText.toLowerCase()) ||
      (user.mobile?.toLowerCase() || '').includes(searchText.toLowerCase())
    );
    setFilteredUsers(filtered);
  }, [searchText, users]);

  const columns: ColumnsType<UserListInfo> = [
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: (gender: string) => (
        <Tag color={gender === 'male' ? 'blue' : 'pink'}>
          {gender === 'male' ? '男性' : '女性'}
        </Tag>
      ),
    },
    {
      title: '生日',
      dataIndex: 'birthDay',
      key: 'birthDay',
      render: (birthDay: number) => {
        try {
          const date = new Date(birthDay);
          return date.toISOString().split('T')[0]; // 返回 YYYY-MM-DD 格式
        } catch {
          return '';
        }
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: number) => (
        <Tag color={role === 2 ? 'red' : 'green'}>
          {role === 2 ? '管理员' : '普通用户'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_deleted',
      key: 'is_deleted',
      render: (is_deleted: boolean) => (
        <Tag color={is_deleted ? 'volcano' : 'green'}>
          {is_deleted ? '停用' : '活跃'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space size="small" wrap>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            size={isMobile ? "small" : "middle"}
          >
            {isMobile ? "" : "编辑"}
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
            disabled={record.role === 2} // Prevent deleting admin users
            size={isMobile ? "small" : "middle"}
          >
            {isMobile ? "" : "删除"}
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingId(null);
    modalForm.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = useCallback((record: UserListInfo) => {
    console.log("编辑用户:", record);
    setEditingId(record.id);
    setIsModalVisible(true);
  }, []);

  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      onOk: async () => {
        try {
          setLoading(true);
          await deleteUser(id);
          setUsers(prevUsers => prevUsers.filter(item => item.id !== id));
          message.success('删除成功');
        } catch (error) {
          console.error('删除用户失败:', error);
          message.error('删除用户失败，请稍后重试');
        } finally {
          setLoading(false);
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await modalForm.validateFields();
      setSubmitting(true);

      const formData = {
        ...values
      };

      if (editingId) {
        // 更新现有用户
        try {
          // 构建只包含已更改字段的数据对象
          const updateData: Partial<UserListInfo> = {
            id: editingId,
            ...formData
          };

          if (formData.birthDay) {
            updateData.birthDay = new Date(formData.birthDay).getTime();
          }

          // 更新用户
          await updateUser(editingId, updateData);

          // 重新获取用户列表
          const data = await getUserList();
          setUsers(data.data);
          setFilteredUsers(data.data);

          message.success('更新成功');
        } catch (error) {
          console.error('更新用户失败:', error);
          message.error('更新用户失败，请稍后重试');
          return;
        }
      } else {
        // 创建新用户
        try {
          const addUserData = {
            mobile: formData.mobile,
            password: formData.password
          };
          const response = await addUser(addUserData);
          const newUser: UserListInfo = {
            id: response.id,
            nickName: response.nick_name || '',
            mobile: response.mobile || addUserData.mobile,
            gender: (response.gender || 'male') as 'male' | 'female',
            birthDay: response.birthDay || 0,
            role: (response.role || 1) as 1 | 2,
            is_deleted: response.is_deleted || false
          };

          // 重新获取用户列表
          const data = await getUserList();
          setUsers(data.data);
          setFilteredUsers(data.data);

          message.success('创建成功');
        } catch (error: any) {
          console.error('创建用户失败:', error);
          // 检查是否有具体的错误信息
          if (error.response?.data?.msg === '用户已存在') {
            message.error('用户已存在');
          } else {
            message.error('创建用户失败，请稍后重试');
          }
          return;
        }
      }

      setIsModalVisible(false);
      modalForm.resetFields();
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const handleUserUpdate = (updatedUser: UserListInfo) => {
    setUsers(prevUsers =>
      prevUsers.map(item =>
        item.id === updatedUser.id ? updatedUser : item
      )
    );
  };

  return (
    <div>
      <Card variant="outlined" className="content-card">
        <div className="page-header" style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '24px',
          flexWrap: 'wrap',
          gap: '16px'
        }}>
          <Title level={4} style={{ margin: 0 }}>用户管理</Title>
          <Space wrap>
            <Input
              placeholder="搜索用户（昵称/手机号）"
              prefix={<SearchOutlined />}
              style={{ width: screens.xs ? '100%' : '200px' }}
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
              allowClear
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加用户
            </Button>
          </Space>
        </div>
        <Table
          columns={columns}
          dataSource={filteredUsers}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: isMobile ? 5 : 10,
            showSizeChanger: !isMobile,
            showQuickJumper: !isMobile,
            showTotal: (total) => `共 ${total} 条记录`,
            responsive: true,
            size: isMobile ? "small" : "default"
          }}
          scroll={{ x: 'max-content' }}
          style={{ overflowX: 'auto' }}
          size={isMobile ? "small" : "middle"}
        />
      </Card>
      <Modal
        title={editingId ? '编辑用户' : '添加用户'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setIsModalVisible(false);
          modalForm.resetFields();
        }}
        confirmLoading={submitting}
      >
        {editingId ? (
          <EditUserForm form={modalForm} editingId={editingId} users={users} setUsers={setUsers} setIsModalVisible={setIsModalVisible} onUserUpdate={handleUserUpdate} />
        ) : (
          <AddUserForm form={modalForm} />
        )}
      </Modal>
    </div>
  );
};

export default UserList;